package com.example.luke.cashorderingsystem.Activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.luke.cashorderingsystem.Common.CommonActivity;
import com.example.luke.cashorderingsystem.Common.Setting;
import com.example.luke.cashorderingsystem.Model.Good;
import com.example.luke.cashorderingsystem.Model.GoodType;
import com.example.luke.cashorderingsystem.Model.Operator;
import com.example.luke.cashorderingsystem.R;
import com.example.luke.cashorderingsystem.Util.ExcelUtils;
import com.example.luke.cashorderingsystem.Util.GlobalFunction;
import com.example.luke.cashorderingsystem.http.HttpClient;
import com.example.luke.cashorderingsystem.http.HttpResponseHandler;
import com.example.luke.cashorderingsystem.http.NetWorkConstant;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import okhttp3.Headers;
import okhttp3.Request;


/**
 * Created by yrdev on 7/18/16.
 */

public class LoginActivity extends CommonActivity {

    public EditText currentEditText;
    ArrayList<GoodType>goodTypeArrayList;
    ArrayList<Good>goodDetailArrayList;
    ArrayList<Operator>operatorArrayList;


    @InjectView(R.id.user_name)EditText userName;
    @InjectView(R.id.user_pass)EditText userPass;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initLanguage(GlobalFunction.getCurrentLanKey(this));


        setContentView(R.layout.login_page_layout);
        GlobalFunction.context=this;

        ButterKnife.inject(this);
        getSupportActionBar().hide();
        initView();


        ExcelUtils.verifyStoragePermissions(this);

//        ExcelUtils.initFoodList();
//
//        GoodType goodType=new GoodType("1","炒菜");
//        GoodType.storeToDB(LoginActivity.this,goodType);

//        ExcelUtils.exportExcel();


    }



    void hideViewKeyboard(){
        hideKeyBoard();
        if (currentEditText!=null){
            currentEditText.setCursorVisible(false);
        }
    }

//    void initView(){

//
//    }


    @Override
    public void initView() {
        super.initView();

        goodTypeArrayList=GoodType.getTypeList(this);
        goodDetailArrayList=Good.getItemDetailList(this);

        Button loginBut=(Button)findViewById(R.id.login);
        loginBut.setOnClickListener(loginListener());
        LinearLayout login_background=(LinearLayout)findViewById(R.id.login_background);
        login_background.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               hideViewKeyboard();
            }
        });

      userName=(EditText)findViewById(R.id.user_name);
      userPass=(EditText)findViewById(R.id.user_pass);


        userName.setOnTouchListener(editTextOnTouchListener());
        userPass.setOnTouchListener(editTextOnTouchListener());

        userName.setOnEditorActionListener(editorActionListener());
        userPass.setOnEditorActionListener(editorActionListener());

//        gotoActivity(CommodityActivity.class,0);

    }

    private  boolean startLogin(){
        boolean stat=false;

        if (userName.getText().toString().length()==0){

            GlobalFunction.ToastAlert(this,GlobalFunction.getString(this,R.string.inputOperId));

            return stat;

        }

        if (userPass.getText().toString().length()==0) {

            GlobalFunction.ToastAlert(this,GlobalFunction.getString(this,R.string.inputOperPass));

            return stat;
        }


        if (userPass.getText().toString().length()>0&& userName.getText().toString().length()>0){
            stat=true;

        }


            return stat;

    }

    View.OnClickListener loginListener(){
        View.OnClickListener login=new View.OnClickListener() {
            @Override
            public void onClick(View view) {


               gotoActivity(HomeActivity.class,0);
                Operator.setInstance(new Operator(userName.getText().toString()));

                ExcelUtils.syncFoodData();



//                if (startLogin()){
//
//                    GlobalFunction.showProgress(LoginActivity.this,GlobalFunction.getString(LoginActivity.this,R.string.notice)
//                            ,GlobalFunction.getString(LoginActivity.this,R.string.isLogin));
//                    getOperatorinfo();
//
//                }


            }
        };
        return login;

    }

    private  boolean existOperator(Operator operator){

        boolean stat=false;

        operatorArrayList=Operator.getOperatorList(this);

        for (Operator op:operatorArrayList){

            if (op.getOperCardNo().equals(operator.getOperCardNo()) ) {

                stat = true;

                break;
            }
        }


        return stat;

    }
    private  void getOperatorinfo(){
        HashMap<String,Object> hashMap=new HashMap<>();
        hashMap.put("operID","");

        HttpClient.postWithFunction(NetWorkConstant.HTTP_getOperatorInfo,hashMap,new HttpResponseHandler(){
            @Override
            protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {

                super.handleSuccessMessage(statusCode, headers, responseBody);
                JSONObject jsonObject;

                try {
                    jsonObject = new JSONObject(responseBody);
                    String response = jsonObject.getString("response");

                    GlobalFunction.printTextByTag(response);

                    JSONObject respBody = new JSONObject(response);
                    String body = respBody.getString("body");

                    JSONObject respItem = new JSONObject(body);


                    JSONArray jsonArray = respItem.getJSONArray("item");

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        Operator operator = new Operator(object);

                        if (!existOperator(operator)) {

                            Operator.saveOperator(LoginActivity.this, operator);

                        }

                        // GoodType.storeToDB(LoginActivity.this,goodType);
                        //   typeAdapter.addJsonObject(object);

                    }


                    if (validUserPass()) {

                        if (goodTypeArrayList.size() == 0) {//没获取过商品类型列表

                            getItemTypeList();
                            return;

                        }

                        if (goodDetailArrayList.size() == 0) {//没获取过商品类型列表

                            getItemDetailList();
                            return;

                        }

                        checkLoginSuccess();

                    } else {

                        GlobalFunction.dismissProgress();
                        GlobalFunction.ToastAlert(LoginActivity.this, GlobalFunction.getString(LoginActivity.this,R.string.inCorOper));

                    }


                } catch (Exception e) {
                    GlobalFunction.dismissProgress();
                    GlobalFunction.ToastAlert(LoginActivity.this, GlobalFunction.getString(LoginActivity.this,R.string.loginFail));

                }

            }

            @Override
            protected void handleFailureMessage(Request request, IOException e) {
                super.handleFailureMessage(request, e);
                GlobalFunction.dismissProgress();
                GlobalFunction.ToastAlert(LoginActivity.this, GlobalFunction.getString(LoginActivity.this,R.string.unReachNet));
            }
        });
    }


    public boolean validUserPass(){
     boolean stat=false;

        for (Operator op:operatorArrayList){
            if (op.getEmployeeID().equals(userName.getText().toString())&&
                    op.getPassword().equals(userPass.getText().toString())){
               stat=true;

            }
        }

        return stat;


    }
    private  void checkLoginSuccess(){
        if (goodTypeArrayList.size()==0){//刷新数组
            goodTypeArrayList=GoodType.getTypeList(this);
        }

        if (goodDetailArrayList.size()==0){//刷新数组
            goodDetailArrayList=Good.getItemDetailList(this);

        }

        if (goodTypeArrayList.size()>0&& goodDetailArrayList.size()>0){
            Intent intent=new Intent(LoginActivity.this,HomeActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            intent.putExtra(GoodType.DH_TABLE_NAME,goodTypeArrayList);
//            intent.putExtra(Good.DH_TABLE_NAME,goodDetailArrayList);

            assignCurrentOperatorInfo();

            Setting.getInstance().init(this);


             GlobalFunction.ToastAlert(LoginActivity.this,GlobalFunction.getString(LoginActivity.this,R.string.loginSuc));
             GlobalFunction.dismissProgress();
            startActivity(intent);
            // gotoActivity(HomeActivity.class,0);

        }

    }

    private void assignCurrentOperatorInfo(){

        try {


            for (Operator op:operatorArrayList){
                if (op.getEmployeeID().equals(userName.getText().toString())){

                    Operator.setInstance(op);

                    break;
                }
            }

            GlobalFunction.printTextByTag(Operator.getIntance().returnCommodityAuthority()+"");
        }catch (Exception e){

        }


    }
    private void getItemTypeList(){//获取商品类型
        HashMap<String,Object> body=new HashMap<>();
        body.put("updateTime","");
        body.put("barcode","");
        body.put("commodityID","");



        HttpClient.postWithFunction(NetWorkConstant.HTTP_getComTypeInfo,body,new HttpResponseHandler(){

            @Override
            protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {
                super.handleSuccessMessage(statusCode, headers, responseBody);


                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responseBody);
                    String response= jsonObject.getString("response");

                    JSONObject respBody=new JSONObject(response);
                    String body=respBody.getString("body");

                    JSONObject respItem=new JSONObject(body);


                    JSONArray jsonArray=respItem.getJSONArray("item");

                    for (int i = 0; i <jsonArray.length() ; i++) {
                        JSONObject object=jsonArray.getJSONObject(i);
                        GoodType goodType=new GoodType(object.getString("id"),object.getString("name"));
                        GoodType.storeToDB(LoginActivity.this,goodType);
                     //   typeAdapter.addJsonObject(object);

                    }

                    getItemDetailList();

                   // typeAdapter.notifyDataSetChanged();

                   // getItemDetail(typeAdapter.getGoodTypeArrayList().get(0).getId());
                    //  selectView(1);//默认第一个选中

                }catch (Exception e){


                    GlobalFunction.ToastAlert(LoginActivity.this,"data is empty");

                }


            }

            @Override
            protected void handleFailureMessage(Request request, IOException e) {
                super.handleFailureMessage(request, e);



            }

        });


    }


    public void goToSetting(View view){
        gotoActivity(SettingActivity.class);

    }

    private void getItemDetailList(){
        if (goodTypeArrayList.size()==0){//刷新数组
            goodTypeArrayList=GoodType.getTypeList(this);
        }




        HttpClient.postWithFunction(NetWorkConstant.HTTP_getComDetailBaseOnType,null,new HttpResponseHandler(){

            @Override
            protected void handleSuccessMessage(int statusCode, Headers headers, String responseBody) {
                super.handleSuccessMessage(statusCode, headers, responseBody);


                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responseBody);
                    String response= jsonObject.getString("response");
                    GlobalFunction.printTextByTag(response);

                    JSONObject respBody=new JSONObject(response);
                    String body=respBody.getString("body");

                    JSONObject respItem=new JSONObject(body);


                    JSONArray jsonArray=respItem.getJSONArray("item");


                    for (int i = 0; i <jsonArray.length() ; i++) {
                        JSONObject object=jsonArray.getJSONObject(i);
                        Good good=new Good(object);

                        Good.storeToDB(LoginActivity.this,good);




                        //goodAdapter.addJsonObject(object);

                    }


                    checkLoginSuccess();

                    //GlobalFunction.printTextByTag("size"+Good.getItemDetailList(LoginActivity.this).size());






//                    itemDetailList.setAdapter(new ArrayAdapter<>(CommodityActivity.this,android.R.layout.simple_list_item_1,goodArrayList));

                }catch (Exception e){
                    GlobalFunction.ToastAlert(LoginActivity.this,"data is empty");
                    GlobalFunction.printTextByTag(e.getMessage());

                }


            }

            @Override
            protected void handleFailureMessage(Request request, IOException e) {
                super.handleFailureMessage(request, e);


            }

        });

    }

    TextView.OnEditorActionListener editorActionListener(){
        TextView.OnEditorActionListener editorActionListener=new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
        hideViewKeyboard();

                return false;
            }
        };
        return editorActionListener;

    }
    View.OnTouchListener editTextOnTouchListener(){
        View.OnTouchListener touchListener=new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                EditText editText=(EditText)view;
                editText.setCursorVisible(true);
                currentEditText=editText;

                return false;

            }
        };
                return touchListener;
    }
    View.OnFocusChangeListener ediTextFocusListener(){
        View.OnFocusChangeListener focusChangeListener=new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {

                InputMethodManager imm = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);

                if (imm.isAcceptingText()) {
                    GlobalFunction.printText("tag","c");
                } else {
                    GlobalFunction.printText("tag","d");
                }
//                EditText editText=(EditText)view;
//                editText.setCursorVisible(true);
            }
        };
                return focusChangeListener;

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);


        if (grantResults[0]== PackageManager.PERMISSION_GRANTED)
            ExcelUtils.creatDir(this,"现金消费");


    }

}
